package servlet;

import run.Call;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by v on 17-7-11.
 */
@WebServlet(name = "Control",value = "/Control")
public class Control extends HttpServlet{
    private static Map<String,ReentrantLock> map=new HashMap<>();
    private static ReentrantLock mapLock=new ReentrantLock();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code=req.getParameter("code");
        String ip=req.getRemoteAddr();

        //对相同的ip地址加锁，保证程序的运行
        ReentrantLock lock;
        //因为哈希表是线程不安全的，而且这里的这个步骤要串行化才能保证运行结果的正确，所以直接使用锁。
        mapLock.lock();
        if(map.containsKey(ip)){
            lock=map.get(ip);
        }else {
            lock=new ReentrantLock();
            map.put(ip,lock);
        }
        mapLock.unlock();

        //并发调用Call
        lock.lock();
        String result=Call.call(code,ip);
        lock.unlock();

        req.getSession().setAttribute("code",result);
        resp.sendRedirect("/return.jsp");
    }
}
